<?php

namespace hangpu8\hpcms\controller;

use \hangpu8\hpcms\Utils\Json;
use Exception;
use hg\apidoc\annotation as Apidoc;
use \hangpu8\hpcms\model\Uploadify as UploadifyModel;
use think\facade\Config;

/**
 * @Apidoc\Title("附件管理")
 */
class Uploadify extends Baseic
{
    // 上传单文件
    public function upload()
    {
        if (request()->isPost()) {
            try {
                $app_upload = Config::get('hpcms.app_upload');
                $field = $this->request->post('field',$app_upload['file_key']);
                $max_size = $this->request->post('max_size',$app_upload['file_size']);
                $file_ext = $this->request->post('file_ext',$app_upload['file_ext']);
                $image_attr = $this->request->post('image_attr');
                $file = request()->file();
                if (!$file) {
                    return Json::fail('文件上传失败');
                }
                // 最大上传容量（单位：KB）
                $fileSize = 1024*50;
                if ($max_size) {
                    // 1M
                    $fileSize = $max_size*100;
                }
                // 限制文件上传格式
                $fileExt = '';
                if ($file_ext) {
                    $fileExt = "|fileExt:{$file_ext}";
                }
                $image = '';
                if ($image_attr) {
                    // 图片尺寸
                    $image = "|image:{$image_attr}";
                }
                $rules = [$field            => "fileSize:{$fileSize}{$fileExt}{$image}"];
                $message = [
                    "$field.fileSize"       => "文件大小不符",
                    "$field.fileExt"        => "仅允许上传{$file_ext}文件格式",
                    "$field.image"          => "文件尺寸必须是：{$image_attr}",
                ];
                validate($rules,$message)
                ->check($file);

                // 定义储存目录
                $uploadKey = 'public';
                // 上传文件
                $filePath = \think\facade\Filesystem::disk($uploadKey)->putFile( 'topic', $file[$field]);
                // 替换文件路径
                $filePath = str_replace("\\",'/',$filePath);
                // 获得上传路径，并转换获得文件目录名
                $getConfig = \think\facade\Filesystem::getConfig();
                $pathName = $getConfig['disks'][$uploadKey]['root'];

                // 组装返回数据
                $pathName = basename($pathName);
                $path = "{$pathName}/{$filePath}";
                $webUrl = getHpConfig('web_url');
                $backData['url'] = "{$webUrl}/{$path}";
                $backData['path'] = $path;

                // 储存上传附件
                $model = new UploadifyModel;
                $data['ctime'] = date('Y-m-d H:i:s');
                $data['filename'] = basename($filePath);
                $data['path'] = $path;
                $data['key'] = substr(basename($filePath),0,strrpos(basename($filePath),"."));
                $data['format'] = substr(basename($filePath),strripos(basename($filePath),".")+1);
                if (!$model->save($data)) {
                    return Json::fail('上传失败，附件库错误');
                }

                // 返回数据
                return Json::successful($backData);
            } catch (\Throwable $e) {
                return Json::fail($e->getMessage());
            }
        } else {
            return Json::fail('请求类型错误');
        }
    }

    // 批量上传文件
    public function uploads()
    {

    }

    /**
     * 查看附件详情
     *
     * @return void
     */
    public function info()
    {

    }
    
    // 列表
    public function index()
    {
        $model = new UploadifyModel;
        $list = $model->order('id desc')->paginate(15)->toArray();
        $builder = new \hangpu8\hpcms\Utils\Builder\ListBuilder;
        $data = $builder
            ->addColumn('rightButtonList', '操作', [
                'type' => 'template',
                'template' => 'rightButtonList'
            ])
            ->addRightButton('info', '详情',[
                'api'               => 'hangpu8/Uploadify/info',
                'title'             => '查看附件详情',
            ])
            ->addRightButton('delete', '删除', [
                'api' => 'hangpu8/Uploadify/del',
                'title' => '确认要删除该数据吗？',
                'modalType' => 'confirm',
                'width' => '600',
                'okText' => '确认删除',
                'cancelText' => '取消操作',
                'content' => '<p>删除该数据不可恢复</p>',
            ])
            ->addColumn('id', '序号')
            ->addColumn('ctime', '创建时间')
            ->addColumn('filename', '文件名')
            ->addColumn('format', '文件格式')
            ->addColumn('key', 'md5外键')
            ->setData($list['data'])
            ->setDataPage($list['total'],$list['per_page'],$list['current_page'])
            ->create();
        return Json::successful($data);
    }
}
